/**
 * Created with JetBrains WebStorm.
 * User: Endre Balogh
 * Date: 6/12/13
 * Time: 9:10 AM
 * To change this template use File | Settings | File Templates.
 */

'use strict';

angular.module('ender.game.town.trainers', [ 'module.ender.game.character.feats', 'ender.game.services', 'ngResource' ])
    .controller('TrainersController', function ($scope, trainerRepository, gameStateService) {
        var trainerIdList = gameStateService.getPlayerCharacter().unlockedTrainers;
        $scope.trainers = trainerRepository.getTrainersByIds(trainerIdList);
    })
    .controller('TrainerController', function ($scope, $routeParams, $location, gameStateService, trainerRepository, featRepository, featHelper) {
        $scope.trainer = trainerRepository.getTrainerById($routeParams.trainerId);
        if (!$scope.trainer) {
            // if repo not loaded yet
            $location.path('/trainers');
        }

        var trainableFeats = featRepository.getFeatsByIds($scope.trainer.trains);
        $scope.$watch(trainableFeats.length, function () {
            function playerAlreadyHasFeat(feat) {
                for (var i = 0, length = $scope.playerCharacter.feats.length; i < length; i++) {
                    var playerFeat = $scope.playerCharacter.feats[i];
                    if (playerFeat.id === feat.id) {
                        return true;
                    }
                }
                return false;
            }

            for (var i = 0, length = trainableFeats.length; i < length; i++) {
                var feat = trainableFeats[i];
                if (playerAlreadyHasFeat(feat)) {
                    feat.disabled = true;
                }
            }

            $scope.trainerFeatCategoryArray = featHelper.buildFeatCategoryArray(trainableFeats);
        });

        function disablePlayerFeats() {
            for (var i = 0, length = $scope.playerCharacter.feats.length; i < length; i++) {
                $scope.playerCharacter.feats[i].disabled = true;
            }
        }

        $scope.playerCharacter = gameStateService.getPlayerCharacter();
        disablePlayerFeats();
        var featsToTrainById = {};
        rebuildCharacterFeatCategoryArray();

        function createFeatsToTrainArray() {
            var featsToTrain = [];
            for (var featId in featsToTrainById) {
                var feat = featsToTrainById[featId];
                if (feat) {
                    featsToTrain.push(feat);
                }
            }
            return featsToTrain;
        }

        function rebuildCharacterFeatCategoryArray() {
            var featsToTrain = createFeatsToTrainArray();
            $scope.characterFeatCategoryArray = featHelper.buildFeatCategoryArray($scope.playerCharacter.feats.concat(featsToTrain));
        }

        // TODO hardcoded value
        $scope.selectedFeatsCost = 12;

        $scope.setSelectedFeat = function (feat) {
            if (!feat.disabled)
                $scope.selectedFeat = feat;
        };

        $scope.addSelectedFeat = function () {
            if ($scope.selectedFeat) {
                featsToTrainById[$scope.selectedFeat.id] = angular.copy($scope.selectedFeat);
                $scope.selectedFeat = null;
                rebuildCharacterFeatCategoryArray();
            }
        };
        $scope.removeSelectedFeat = function () {
            if ($scope.selectedFeat) {
                featsToTrainById[$scope.selectedFeat.id] = null;
                $scope.selectedFeat = null;
                rebuildCharacterFeatCategoryArray();
            }
        };
        $scope.removeAllFeats = function () {
            featsToTrainById = {};
            $scope.selectedFeat = null;
            rebuildCharacterFeatCategoryArray();
        };
        $scope.cancel = function () {
            $location.path('/trainers');
        };
        $scope.trainSelected = function () {
            $scope.playerCharacter.feats = $scope.playerCharacter.feats.concat(createFeatsToTrainArray());
        };
    })
    .factory('trainerRepository', function factoryFunction($resource, $q) {
        var resource = $resource('data/trainers.json');
        var deferred = $q.defer();
        var trainersResource = resource.get(function () {
            for (var trainerId in trainersResource) {
                if (trainersResource.hasOwnProperty(trainerId)) {
                    var trainer = trainersResource[trainerId];
                    trainer.id = trainerId;
                }
            }

            deferred.resolve();
        });

        return {
            /**
             * Returns the trainers with the given ids. The result is an empty array, which will be filled when the data will be available.
             * @param {Array} trainerIdList
             * @returns {Array}
             */
            getTrainersByIds: function (trainerIdList) {
                var trainers = [];

                deferred.promise.then(function () {
                    for (var i = 0, length = trainerIdList.length; i < length; i++) {
                        var trainerId = trainerIdList[i];
                        trainers.push(trainersResource[trainerId]);
                    }
                });

                return trainers;
            },
            /**
             * Returns the trainer with the given id. The result is undefined if the data is not yet loaded or if there is no trainer with the given id.
             * @param {String} trainerId
             */
            getTrainerById: function (trainerId) {
                return trainersResource[trainerId];
            }
        }
    });
